package com.cscp.javastudy.basic.reflect;

import com.cscp.javastudy.designpattern.adapter.demo1.NetToUsb;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 获取类的信息
 */
public class ClassInfo {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.cscp.javastudy.basic.reflect.User");
        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());

        User user = new User();
        Class c2 = user.getClass();
        System.out.println(c2.getName());
        System.out.println(c2.getSimpleName());

        c1.getFields();// 或者public的属性

        // 获得类的属性
        Field[] declaredFields = c1.getDeclaredFields();// 获得所有的属性
        for (Field field : declaredFields){
            System.out.println(field);
        }
        // 获得指定属性的名字
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        // 获得类的方法
        Method[] declaredMethods = c1.getDeclaredMethods();// 获取所有的method
        System.out.println("====== Method: ");
        for (Method method : declaredMethods) {
            System.out.println(method);
        }
        System.out.println("====== 获取指定的方法：");
        Class c3 = Class.forName("com.cscp.javastudy.designpattern.adapter.demo1.Computer");
        Method net = c3.getDeclaredMethod("net", NetToUsb.class);
        System.out.println(net);
        System.out.println("====== 获取指定的构造器：");
        Constructor[] declaredConstructors = c1.getDeclaredConstructors();
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor);
        }

    }
}
